package com.wedo.mall.util;

import android.os.Parcelable;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

/**
 * 使用软引用解决android.os.TransactionTooLargeException
 * @author lxy
 * @time 2018/5/15  9:50
 * @see android.os.TransactionTooLargeException
 */
public final class ParcelableTransaction<T extends Parcelable> {

    public static final String KEY_LIST = "list";
    public static final String KEY_DATA = "data";

    private static transient ParcelableTransaction instance;

    public static ParcelableTransaction with() {
        if (instance == null) {
            synchronized (ParcelableTransaction.class) {
                if (instance == null) {
                    instance = new ParcelableTransaction();
                }
            }
        }

        return instance;
    }

    private HashMap<String,WeakReference<T>> parcelableMap = new HashMap<>();
    private HashMap<String,WeakReference<List<T>>> parcelableListMap = new HashMap<>();

    private ParcelableTransaction() {
    }

    public void starActivity(List<T> list){
        putParcelableList(KEY_LIST,list);
    }

    public void starActivity(T parcelable){
        putParcelable(KEY_DATA,parcelable);
    }

    public void putParcelable(String key, T parcelable){
        parcelableMap.put(key,new WeakReference<>(parcelable));
    }

    public void putParcelableList(String key, List<T> list){
        parcelableListMap.put(key,new WeakReference<>(list));
    }

    public Parcelable data(){
        return getParcelable(KEY_DATA);
    }

    public T getParcelable(String key){
        if(parcelableMap.containsKey(key)) {
            WeakReference<T> reference = parcelableMap.get(key);
            return reference.get();
        }

        return null;
    }

    public List<T> list(){
        return getParcelableList(KEY_LIST);
    }

    public List<T> getParcelableList(String key){
        if(parcelableListMap.containsKey(key)) {
            WeakReference<List<T>> reference = parcelableListMap.get(key);
            return reference.get();
        }

        return null;
    }

    public boolean containsParcelable(String key){
        return parcelableMap.containsKey(key);
    }

    public boolean containsParcelableList(String key){
        return parcelableListMap.containsKey(key);
    }

}
